<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BrowserRouter 的实现原理</title>
    <style>
      #result {
        width: 400px;
        height: 300px;
        border: solid 1px #ddd;
      }
    </style>
  </head>
  <body>
    <a href="/home">Home</a>
    <a href="/about">About</a>

    <hr />
    <div id="result"></div>

    <script>
      //获取 result 元素
      let result = document.getElementById("result");
      let links = document.querySelectorAll("a");

      //绑定事件
      links.forEach((link) => {
        //单个 a 元素绑定事件
        link.onclick = function (e) {
          //阻止默认行为
          e.preventDefault();
          //获取当前所点 a 元素的 href 值
          let href = this.href;
          //改变页面的 URL 内容
          history.pushState({ id: 100 }, "", href);
          //获取网页 URL 的路径
          let { pathname } = location;
          //根据 url 的路径设置 div 中的内容
          switch (pathname) {
            case "/home":
              result.innerHTML = "Home Home Home";
              break;
            case "/about":
              result.innerHTML = "About About About";
              break;
            default:
              result.innerHTML = "404 Not Found";
              break;
          }
        };
      });

      //全局事件 popstate   从历史栈结构中, 弹出记录时会触发该事件
      window.addEventListener("popstate", function () {
        //获取网页 URL 的路径
        let { pathname } = location;
        //根据 url 的路径设置 div 中的内容
        switch (pathname) {
          case "/home":
            result.innerHTML = "Home Home Home";
            break;
          case "/about":
            result.innerHTML = "About About About";
            break;
          default:
            result.innerHTML = "404 Not Found";
            break;
        }
      });
    </script>
  </body>
</html>
